package com.kashow.base;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.jaeger.library.StatusBarUtil;
import com.kashow.AppContext;
import com.kashow.R;
import com.kashow.injector.component.ActivityComponent;
import com.kashow.injector.component.ApplicationComponent;
import com.kashow.injector.module.ActivityModule;
import com.orhanobut.logger.Logger;
import com.trello.rxlifecycle.LifecycleTransformer;
import com.trello.rxlifecycle.RxLifecycle;
import com.trello.rxlifecycle.android.ActivityEvent;
import com.trello.rxlifecycle.android.RxLifecycleAndroid;
import com.zhy.autolayout.AutoFrameLayout;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import javax.inject.Inject;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.yokeyword.fragmentation.SupportActivity;
import rx.Observable;
import rx.subjects.BehaviorSubject;

public abstract class BaseActivity<T extends RxPresenter> extends SupportActivity {

    private static final String LAYOUT_LINEARLAYOUT = "LinearLayout";
    private static final String LAYOUT_FRAMELAYOUT = "FrameLayout";
    private static final String LAYOUT_RELATIVELAYOUT = "RelativeLayout";
    private final String TAG = BaseActivity.this.getClass().getSimpleName();

    private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create();
    private Unbinder mUnBinder;

    @NonNull
    @CheckResult
    public final Observable<ActivityEvent> lifecycle() {
        return lifecycleSubject.asObservable();
    }

    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull ActivityEvent event) {
        return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
    }

    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindToLifecycle() {
        return RxLifecycleAndroid.bindActivity(lifecycleSubject);
    }

    protected ActivityComponent mActivityComponent;
    @Inject
    protected T mPresenter;

    @Inject
    AppManager mAppManager;

    protected Context mContext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        lifecycleSubject.onNext(ActivityEvent.CREATE);
        mActivityComponent = setupActivityComponent(((AppContext) getApplication()).component());
        super.onCreate(savedInstanceState);
        this.setContentView(this.getLayoutId());
        mContext = this;
        setUpStatusBar();
        mUnBinder = ButterKnife.bind(this);
        initInject();
        mAppManager.addActivity(this);
        if (this instanceof BaseView) mPresenter.attachView(this);
        initEventAndData();

        Logger.d("----activity----%s----life----->%s-----",this.getClass().getSimpleName(),"onCreate");

    }


    protected void setUpStatusBar() {
        StatusBarUtil.setColor(BaseActivity.this, getStatusBarColor());
    };

    public abstract int getLayoutId();
    public abstract void initInject();
    public abstract void initEventAndData();

    public int getStatusBarColor() {
        return AppCompat.getColor(R.color.colorPrimary,mContext.getApplicationContext());
    }

    protected ActivityComponent setupActivityComponent(ApplicationComponent applicationComponent) {
        return DaggerActivityComponent.builder()
                .applicationComponent(applicationComponent)
                .activityModule(new ActivityModule(this))
                .build();
    }


    @Override
    @CallSuper
    protected void onStart() {
        super.onStart();
        lifecycleSubject.onNext(ActivityEvent.START);

        Uri mLink = getIntent().getData();

        Logger.d("----activity----%s----life----->%s-----",this.getClass().getSimpleName(),"onStart");
    }

    @Override
    @CallSuper
    protected void onResume() {
        super.onResume();
        lifecycleSubject.onNext(ActivityEvent.RESUME);
        Logger.d("----activity----%s----life----->%s-----",this.getClass().getSimpleName(),"onResume");
    }

    protected String getTagName() {
        return TAG;
    }

    @Override
    @CallSuper
    protected void onPause() {
        lifecycleSubject.onNext(ActivityEvent.PAUSE);
        super.onPause();
        Logger.d("----activity----%s----life----->%s-----",this.getClass().getSimpleName(),"onPause");
    }

    @Override
    @CallSuper
    protected void onStop() {
        lifecycleSubject.onNext(ActivityEvent.STOP);
        super.onStop();
        Logger.d("----activity----%s----life----->%s-----",this.getClass().getSimpleName(),"onStop");
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }

    @Override
    @CallSuper
    protected void onDestroy() {
        lifecycleSubject.onNext(ActivityEvent.STOP);
        if (mPresenter != null) mPresenter.detachView();
        mUnBinder.unbind();
        super.onDestroy();
        Logger.d("----activity----%s----life----->%s-----",this.getClass().getSimpleName(),"onDestroy");
    }

    public <F> LifecycleTransformer<F> bindUntilActivityEvent(ActivityEvent event) {
        return bindUntilEvent(event);
    }

    protected void setToolBar(Toolbar toolbar,String title) {
        toolbar.setTitle(title);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressedSupport();
            }
        });
    }

    protected void setToolBar(Toolbar toolbar) {
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_back_light);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressedSupport();
            }
        });
    }

    public void useNightMode(boolean isNight) {
        if (isNight) {
            AppCompatDelegate.setDefaultNightMode(
                    AppCompatDelegate.MODE_NIGHT_YES);
        } else {
            AppCompatDelegate.setDefaultNightMode(
                    AppCompatDelegate.MODE_NIGHT_NO);
        }
        recreate();
    }

    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        View view = null;
        if (name.equals(LAYOUT_FRAMELAYOUT)) {
            view = new AutoFrameLayout(context, attrs);
        }

        if (name.equals(LAYOUT_LINEARLAYOUT)){
            view = new AutoLinearLayout(context, attrs);
        }

        if (name.equals(LAYOUT_RELATIVELAYOUT)){
            view = new AutoRelativeLayout(context, attrs);
        }

        if (view != null) return view;

        return super.onCreateView(name, context, attrs);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }


    protected void finishActivity() {
        mAppManager.finishActivity(this);
    }
}
